"""
LCEL Routing Chain Demo

This script demonstrates the modern LCEL approach to routing chains
and compares it with traditional methods.
"""

from app.services.lcel_routing_service import LCELRoutingService
from app.services.routing_chain_service import RoutingChainService
from app.services.chat_service_simple import ChatServiceSimple
import time


def demo_lcel_vs_traditional():
    """
    Compare LCEL approach with traditional routing approaches
    """

    test_queries = [
        {
            "category": "生肖查询",
            "query": "我1990年出生，属什么生肖？"
        },
        {
            "category": "系统查询",
            "query": "当前服务器负载情况如何？"
        },
        {
            "category": "数学计算",
            "query": "计算 25 * 4 + 10 等于多少？"
        },
        {
            "category": "一般对话",
            "query": "请介绍一下机器学习"
        }
    ]

    print("🚀 LCEL vs 传统路由链对比")
    print("=" * 60)

    # Initialize services
    lcel_service = LCELRoutingService()
    traditional_service = RoutingChainService()
    agent_service = ChatServiceSimple()

    for i, test_case in enumerate(test_queries, 1):
        print(f"\n📝 测试 {i}: {test_case['category']}")
        print(f"问题: {test_case['query']}")
        print("-" * 40)

        # Test LCEL RunnableBranch approach
        print("🔗 LCEL RunnableBranch:")
        try:
            start_time = time.time()
            lcel_chain = lcel_service.create_routing_branch_lcel()
            lcel_result = lcel_chain.invoke(test_case['query'])
            lcel_time = time.time() - start_time
            print(f"结果: {lcel_result[:150]}...")
            print(f"耗时: {lcel_time:.3f}秒")
        except Exception as e:
            print(f"错误: {e}")

        print()

        # Test traditional semantic routing
        print("🔄 传统语义路由:")
        try:
            start_time = time.time()
            traditional_chain = traditional_service.create_semantic_routing_chain()
            traditional_result = traditional_chain(test_case['query'])
            traditional_time = time.time() - start_time
            print(f"结果: {traditional_result[:150]}...")
            print(f"耗时: {traditional_time:.3f}秒")
        except Exception as e:
            print(f"错误: {e}")

        print()

        # Test Agent tool approach
        print("🤖 Agent工具模式:")
        try:
            start_time = time.time()
            # Simplified agent simulation
            query = test_case['query']
            if test_case['category'] == "生肖查询":
                result = agent_service._get_zodiac_sign(1990)
            elif test_case['category'] == "系统查询":
                result = agent_service._handle_system_query(query)
            elif test_case['category'] == "数学计算":
                result = agent_service._calculate("25 * 4 + 10")
            else:
                result = "Agent直接回答模式"
            agent_time = time.time() - start_time
            print(f"结果: {result[:150]}...")
            print(f"耗时: {agent_time:.3f}秒")
        except Exception as e:
            print(f"错误: {e}")

        print("\n" + "=" * 60)


def demo_lcel_approaches():
    """
    Demonstrate different LCEL routing approaches
    """

    query = "1990年是什么生肖？服务器负载如何？"

    print(f"\n🔀 不同LCEL路由方法对比")
    print(f"测试问题: {query}")
    print("=" * 50)

    lcel_service = LCELRoutingService()

    # Test different LCEL approaches
    approaches = [
        ("RunnableBranch", lcel_service.create_routing_branch_lcel()),
        ("Composed Routing", lcel_service.create_composed_routing_lcel()),
        ("Parallel Routing", lcel_service.create_parallel_routing_lcel())
    ]

    for name, chain in approaches:
        print(f"\n{name}:")
        try:
            start_time = time.time()
            result = chain.invoke(query)
            elapsed = time.time() - start_time
            print(f"结果: {result[:150]}...")
            print(f"耗时: {elapsed:.3f}秒")
        except Exception as e:
            print(f"错误: {e}")


def show_lcel_syntax_examples():
    """
    Show LCEL syntax examples and benefits
    """

    print("\n📝 LCEL语法示例")
    print("=" * 40)

    print("🔧 传统链式调用:")
    print("""
chain = prompt_template.format_messages(query)
result = llm.invoke(chain)
output = parser.parse(result.content)
    """)

    print("\n⚡ LCEL语法 (现代方式):")
    print("""
chain = prompt_template | llm | parser
result = chain.invoke(query)
    """)

    print("\n🎯 LCEL路由链示例:")
    print("""
# 定义路由分支
routing_chain = RunnableBranch(
    (lambda x: "生肖" in x, zodiac_chain),
    (lambda x: "系统" in x, system_chain),
    (lambda x: "计算" in x, calculation_chain),
    general_chain
)

# 直接调用
result = routing_chain.invoke(query)
    """)

    print("\n✨ LCEL优势:")
    print("• ✅ 代码简洁，使用管道符 | 连接")
    print("• ✅ 类型安全，更好的IDE支持")
    print("• ✅ 自动批处理和流式支持")
    print("• ✅ 内置错误处理和重试机制")
    print("• ✅ 更好的性能优化")
    print("• ✅ LangChain官方推荐方式")


def performance_comparison():
    """
    Performance comparison between different approaches
    """

    print("\n⚡ 性能对比测试")
    print("=" * 40)

    query = "1990年出生的人属什么生肖？"
    iterations = 20

    lcel_service = LCELRoutingService()
    traditional_service = RoutingChainService()

    # Test LCEL performance
    lcel_chain = lcel_service.create_routing_branch_lcel()
    start_time = time.time()
    for _ in range(iterations):
        try:
            lcel_chain.invoke(query)
        except:
            pass
    lcel_total = time.time() - start_time

    # Test traditional performance
    traditional_chain = traditional_service.create_semantic_routing_chain()
    start_time = time.time()
    for _ in range(iterations):
        try:
            traditional_chain(query)
        except:
            pass
    traditional_total = time.time() - start_time

    print(f"测试查询: {query}")
    print(f"迭代次数: {iterations}")
    print(f"LCEL RunnableBranch: {lcel_total:.3f}秒 (平均 {lcel_total/iterations:.3f}秒/次)")
    print(f"传统语义路由: {traditional_total:.3f}秒 (平均 {traditional_total/iterations:.3f}秒/次)")
    print(f"性能提升: {((traditional_total - lcel_total) / traditional_total * 100):.1f}%")


if __name__ == "__main__":
    print("🚀 LCEL路由链模式演示")
    print("=" * 60)

    # Run demos
    demo_lcel_vs_traditional()
    demo_lcel_approaches()
    show_lcel_syntax_examples()
    performance_comparison()

    print("\n✅ 演示完成")
    print("\n🎯 总结:")
    print("• LCEL是LangChain官方推荐的现代语法")
    print("• RunnableBranch提供了优雅的路由解决方案")
    print("• LCEL代码更简洁，性能更好")
    print("• 支持流式处理、批处理等高级特性")